<!--
* description: 备件奖励金操作
* author: xiaochengzuan
* createdDate: 2021-1-25
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :dynamic-api-style="'restful'"
      :callback-obj="callBackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      :dynamic-api-style="'restful'"
      @close="close"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from './api'
import { exportExcel } from '@/utils/exportExcel'

export default {
  name: 'SparePartsBonusOperation',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // this.$refs['multipleTable'].data = [{bigAreaCode:'1'}]
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      callBackObj: {
        onCheckSelectChange: (selection) => {
          this.selectData = selection
        }
      },
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryBonusOrderOperatePage,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'add',
          clickEvent: this.add,
          text: this.$t('sys.button.add'), // 新增
          position: 'right'
        },
        {
          compKey: 'comKey3',
          type: '',
          size: 'small',
          name: '',
          position: 'right',
          clickEvent: () => {
            this.auditByType('pass')
          },
          text: '提交',
          disabled: false
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          clickEvent: () => {
            this.auditByType()
          },
          text: '作废',
          name: '',
          position: 'right'
        //   fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          type: '',
          size: 'small',
          name: 'export',
          position: 'right',
          clickEvent: () => exportExcel.call(this, api.exoprtBonusBusiReview.APIUrl), // 导出
          text: '导出'

        },
        {
          compKey: 'btnKey2',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        }
        //      {
        //   compKey: 'btnKey2',
        //   type: '',
        //   size: 'small',
        //   name: 'reset',
        // //   clickEvent: () => this.reset(),
        //   text: '导入',
        //   position: 'left' // 导入
        // },

      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '操作单号：',
              codeField: 'dlrDiscountOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'comKey2',
              labelName: '网点名称：',
              codeField: 'dlrCode',
              textField: 'dlrShortName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              type: 'inputText',
              isMust: true,
              dataToObject: {
                oFields: 'dlrCode,dlrShortName',
                // 控制弹窗页面 搜索 网格 元素
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                returnField: {
                  prop: 'dlrShortName',
                  label: '网点名称'
                },
                api: api.queryOrgDlrCodes
              },
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '审核状态：',
              codeField: 'discountStatus',
              textField: 'discountStatusCn',
              component: () => import('@/components/org/commonSelect'),
              // customObj: {
              //   listQuery: { },
              //   api: { APIUrl: '/mp/e3sh/spareparts/finance/bonusOrderMakeService/queryBonusStatus' },
              //   selectType: '1'
              // },
              oFields: 'c,n',
              options: [
                { c: '0', n: '保存' },
                { c: '1', n: '提交' },
                { c: '2', n: '通过' },
                { c: '3', n: '驳回' },
                { c: '4', n: '作废' }
              ],
              type: 'dropdownList',
              // isMul: true,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey4',
              labelName: '红色通知单号：',
              codeField: 'redNoticeNumber',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey5',
              labelName: '操作类型：',
              codeField: 'actionType',
              textField: 'actionTypeCn',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'actionType,actionTypeCn',
              options: [
                { actionType: '1', actionTypeCn: '上账' },
                { actionType: '0', actionTypeCn: '冻结' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true,
              span: 6
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn1',
              label: '操作',
              minWidth: 180,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '修改',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                }
              ]
            },
            {
              prop: 'dlrCode',
              label: '网点编码',
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'discountAccount',
              label: '奖励金余额'
            },
            {
              prop: 'frozenMoney',
              label: '可用金额'
            },
            {
              prop: 'actionTypeCn',
              label: '操作类型'
            },
            {
              prop: 'account',
              label: '操作金额'
            },
            {
              prop: 'remark',
              label: '原因'
            },
            {
              prop: 'redNoticeNumber',
              label: '红色通知单号'
            },
            {
              prop: 'dlrDiscountOrderCode',
              label: '操作单号'
            },
            {
              prop: 'discountStatusCn',
              label: '审核状态'
            },
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间'
            }

          ],
      // 表单查询数据
      formField: {},
      selectData: []
    }
  },

  created() {
    this.genFormField()
  },
  mounted() {
  },

  methods: {
    auditByType(type) {
      // 提交和作废 api
      const apiUrl = type === 'pass'
        ? api.editBonusOrderOperateSubmit.APIUrl
        : api.editBonusOrderOperateInvalid.APIUrl
      this.$requestAPI({
        apiUrl,
        variables: {
          bonusOrderStatus: this.selectData.reduce((pre, cur, idx) => {
            const { dlrDiscountOrderId, updateControlId } = cur
            pre.push({ dlrDiscountOrderId, updateControlId })
            return pre
          }, [])
        }
      }).then(response => {
        if (response.result === '1') {
          this.queryTable()
          this.$message(type === 'pass' ? '提交成功!' : '作废成功!')
        } else {
          this.$message(response.msg)
        }
      }).catch(err => {
        // loading.close()
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },
    // 编辑获取数据
    edit(index) {
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      if (this.resetDialogKey === true) {
        this.editPopupsKey = this.$utils.generateId()
      }
    },
    genFormField() {
      const viewPageCode = this.$route.path
      this.genCodeFiled = this.genUtil(this.tableComponents)
      const formField = this.genCodeFiled()
      this.formField = this.$utils.getFormField(this, formField, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    },
    // 生成formField
    genUtil: (array) => (attr1 = 'codeField', attr2 = 'textField') => array.reduce((p, c) => {
      p[c[attr1]] = ''
      // eslint-disable-next-line no-prototype-builtins
      c.hasOwnProperty(attr2) ? p[c[attr2]] = '' : ''
      return p
    }, {})
  }
}
</script>
